package com.fuyun.rpc.provider.impl;

import cn.hutool.core.collection.CollUtil;
import com.fuyun.rpc.config.RpcServiceConfig;
import com.fuyun.rpc.exception.RpcException;
import com.fuyun.rpc.provider.ServiceProvider;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author fuyun。
 * @Date 2025/8/21 17:12。
 * @Description: TODO。
 **/

@Slf4j
public class SimpleServiceProvider implements ServiceProvider {

    private final Map<String, Object> SERVER_CACHE = new ConcurrentHashMap<>();


    @Override
    public void publishService(RpcServiceConfig config) {
        List<String> rpcServerNames = config.rpcServerNames();
        if (CollUtil.isEmpty(rpcServerNames)) {
            throw new RpcException("该服务没有实现接口");
        }
        log.debug("发布服务 {}", rpcServerNames);
        rpcServerNames.forEach(rpcServerName -> SERVER_CACHE.put(rpcServerName, config.getService()));
    }

    @Override
    public Object getService(String serviceName) {
        if (!SERVER_CACHE.containsKey(serviceName)) {
            throw new RuntimeException("找不到服务： " + serviceName);
        }
        return SERVER_CACHE.get(serviceName);
    }
}
